package com.shd.edanpei.presenter;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.shd.edanpei.BuildConfig;
import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.network.ApiConstant;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.UserBean;
import com.shd.edanpei.presenter.contract.LoginContract;
import com.shd.edanpei.customer.activity.CMainActivity;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.ui.activity.RegisterResultActivity;
import com.shd.edanpei.ui.activity.CertificationActivity;
import com.shd.edanpei.ui.activity.MainActivity;
import com.shd.edanpei.ui.activity.PerfectDataActivity;
import com.shd.edanpei.ui.activity.RoleChoiceActivity;
import com.shd.edanpei.util.LoginUtils;
import com.shd.edanpei.util.MD5Util;
import com.shd.edanpei.util.ToastUtil;
import com.shd.edanpei.util.Validator;

import io.reactivex.android.schedulers.AndroidSchedulers;

public class LoginPresenter extends BasePresenterImpl<LoginContract.LoginIView>
        implements LoginContract.LoginIPresenter {


    private static final int SUCCESS = 100;
    private static final int ERROR = 101;
    private static final int CANCEL = 102;

    private static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:

                    break;
                case ERROR:
                    ToastUtil.showToast(msg.obj + "");
                    break;
                case CANCEL:

                    break;
            }
        }
    };

    public LoginPresenter(LoginContract.LoginIView mView) {
        super(mView);
    }

    @Override
    public void login(final String phone, final String password,final int loginType,final String checkCode) {
        if (!Validator.isMobile(phone)) {
            ToastUtil.showToast("请输入正确手机号");
            return;
        }
        mBaseIView.showLoading("登录中...");
        ApiCreator.getApi().login(phone, MD5Util.MD5Encode(password, ""),loginType,checkCode, BuildConfig.APPDONLOADSSOURE)
                .compose(RxTransformer.<UserBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UserBean>() {
                    @Override
                    protected void onSuccess(UserBean data) {
                        DaoManager.getInstance().saveUserBean(data);
                        Constant.roleType = data.getRoleType();
                        loginVerify(data);
                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });

//        ApiCreator.getApi().test()
//                .compose(RxTransformer.<UserBean> errorHandle())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new BaseObserver<UserBean>() {
//                    @Override
//                    protected void onSuccess(UserBean data) {
//                        ToastUtil.showToast("test");
//                    }
//                });
    }


    @Override
    public void getCAPTCHA(String phone,String uuid,String code) {
        if (!Validator.isMobile(phone)) {
            ToastUtil.showToast("请输入正确手机号");
            return;
        }
        mBaseIView.getCAPTCHAView().setClickable(false);
        ApiCreator.getApi().sendSms(phone, 1,code,uuid)
                                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new BaseObserver<NoDataResponse>() {
                                            @Override
                                            protected void onSuccess(NoDataResponse data) {
                                                ToastUtil.showToast("短信发送成功");
                                                new CountDownTimer(60 * 1000, 1 * 1000) {

                                                    @Override
                                                    public void onTick(long l) {
                                                        if (null != mBaseIView.getCAPTCHAView()) {
                                                            mBaseIView.getCAPTCHAView().setText(l / 1000 + "s");
                                                        }
                                                    }

                                                    @Override
                                                    public void onFinish() {
                                                        if (null != mBaseIView.getCAPTCHAView()) {
                                    mBaseIView.getCAPTCHAView().setClickable(true);
                                    mBaseIView.getCAPTCHAView().setText("获取验证码");
                                }
                            }


                        }.start();
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getCAPTCHAView().setClickable(true);
                        mBaseIView.getCAPTCHAView().setText("获取验证码");
                    }
                });
    }



    @Override
    public void getLoginCode(String phone,String uuid,String code) {
        if (!Validator.isMobile(phone)) {
            ToastUtil.showToast("请输入正确手机号");
            return;
        }
        mBaseIView.getLoginCode().setClickable(false);
        ApiCreator.getApi().sendSms(phone, 37,code,uuid)//获取登录验证码类型37
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {
                        ToastUtil.showToast("短信发送成功");
                        new CountDownTimer(60 * 1000, 1 * 1000) {

                            @Override
                            public void onTick(long l) {
                                if (null != mBaseIView.getCAPTCHAView()) {
                                    mBaseIView.getLoginCode().setText(l / 1000 + "s");
                                }
                            }

                            @Override
                            public void onFinish() {
                                if (null != mBaseIView.getCAPTCHAView()) {
                                    mBaseIView.getLoginCode().setClickable(true);
                                    mBaseIView.getLoginCode().setText("获取验证码");
                                }
                            }


                        }.start();
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getCAPTCHAView().setClickable(true);
                        mBaseIView.getCAPTCHAView().setText("获取验证码");
                    }
                });

    }

    @Override
    public void signUp(final String phone, final String code, String password1, String password2) {
        if (!Validator.isMobile(phone)) {
            ToastUtil.showToast("请输入正确手机号");
            return;
        }
        if (password1.length() < 8 || password2.length() < 8) {
            ToastUtil.showToast("请设置至少8位密码");
            return;
        }
        if(!LoginUtils.ispsd(password1)){
            ToastUtil.showToast("密码为8至16位数字密码组合，请正确输入!");
            return;
        }

        if (!password1.equals(password2)) {
            ToastUtil.showToast("两次密码不一致");
            return;
        }
        mBaseIView.showLoading("注册中...");
        ApiCreator.getApi().signup(phone, code, MD5Util.MD5Encode(password1, ""), "","安卓")
                .compose(RxTransformer.<UserBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UserBean>() {
                    @Override
                    protected void onSuccess(UserBean data) {
                        ToastUtil.showToast("注册成功");
                        DaoManager.getInstance().saveUserBean(data);

                        //进入身份选择
                        mBaseIView.startActivity(RoleChoiceActivity.class);
                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
    }

    private void loginVerify(UserBean bean) {
        if (bean.getState() == RegisterResultActivity.freeze){
            // 冻结
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.TYPE, bean.getState());
            mBaseIView.startActivity(RegisterResultActivity.class, bundle);
        } else{
            //未冻结
            switch (bean.getRoleType()) {
                case 0:
                    //未知角色
                    mBaseIView.startActivity(RoleChoiceActivity.class);
                    break;
                case 1:
                    //C端用户
                    mBaseIView.startActivity(CMainActivity.class);
                    break;
                case 4:
                case 5:
                    //中介
                    mBaseIView.startActivity(MainActivity.class);
                    break;
                default:
                    //其他角色
                    if (bean.isReal()) {
                        //已实名认证
                        if (bean.isPerfectInfo()) {
                            //已完善资料
                            if (bean.getState() == RegisterResultActivity.normal) {
                                mBaseIView.startActivity(MainActivity.class);
                            } else if (bean.getState() == RegisterResultActivity.apply
                                    || bean.getState() == RegisterResultActivity.refuse
                                    || bean.getState() == RegisterResultActivity.freeze) {
                                Bundle bundle = new Bundle();
                                bundle.putInt(Constant.TYPE, bean.getState());
                                mBaseIView.startActivity(RegisterResultActivity.class, bundle);
                            }
                        } else {
                            //未完善资料
                            mBaseIView.startActivity(PerfectDataActivity.class);
                        }
                    } else {
                        //未实名认证
                        Bundle bundle = new Bundle();
                        bundle.putInt(Constant.FROM, CertificationActivity.FROM_LOGIN);
                        mBaseIView.startActivity(CertificationActivity.class, bundle);
                    }
                    break;
            }
        }
        mBaseIView.getContext().finish();
    }

}
